//
//  ViewController.m
//  HelloMyMap
//
//  Created by Joe Chen on 2016/5/18.
//  Copyright © 2016年 Joe Chen. All rights reserved.
//

#import "ViewController.h"
#import "RecordPositionViewController.h"
#import "MapAnnotation.h"

#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

#warning https://www.baidu.com/s?wd=mkmapview%20%E8%B4%B4%E5%9B%BE&rsv_spt=1&rsv_iqid=0xf60d84c70002ce01&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_sug3=19&rsv_sug1=13&rsv_sug7=101&sug=mkmapview&rsv_n=1&rsv_sug2=0&inputT=26990&rsv_sug4=48951


@interface ViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet MKMapView *mainMapView;
@property (strong,nonatomic) CLLocationManager *locationManager;
@property (strong,nonatomic) NSMutableArray *saveLocation;
@property (strong,nonatomic) NSMutableArray<NSValue *> *saveCoor;
@property (assign,nonatomic) CLLocationCoordinate2D coor;
@property (assign,nonatomic) NSInteger trackingIndex;

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray * notesFromUserDefault = [userDefaults objectForKey:@"notes"];
    
    if (notesFromUserDefault == nil) {
        _saveLocation = [NSMutableArray array];
    } else {
        _saveLocation = [NSMutableArray arrayWithArray:notesFromUserDefault];
    }
    _saveCoor = [NSMutableArray array];
    [[CLLocationManager new] requestAlwaysAuthorization];
    _locationManager = [CLLocationManager new]; // =[[CLLocationManager alloc]init];
    //判斷ios版本有無支援使用者位置授權,ios8以後才支援
    //respondsToSelector 檢查locationManager 有無支援,這方法常用
    if([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
        [_locationManager requestWhenInUseAuthorization];
    }
//    [_locationManager requestAlwaysAuthorization];
//
//    //prepare locationManager
//    _locationManager.distanceFilter = kCLDistanceFilterNone;
//    _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
//    _locationManager.activityType = CLActivityTypeAutomotiveNavigation; //什麼類型的運用（運動 汽車...)
//    _locationManager.delegate = self; //locationManager回報時回報到self
}

- (IBAction)returnUserPosition:(id)sender {
    
    NSInteger returnIndex = [sender selectedSegmentIndex];
    
    if(returnIndex == 1  ){
        [_locationManager startUpdatingLocation]; //開始回報位置
    }else{
        [_locationManager stopUpdatingLocation];
    }
}


- (IBAction)trackingModeChange:(id)sender {
    NSInteger targetIndex = [sender selectedSegmentIndex];
    
    [_mainMapView setShowsUserLocation:YES];
    switch (targetIndex) {
        case 0:
            _mainMapView.userTrackingMode = MKUserTrackingModeNone;
            [_mainMapView removeOverlays:[_mainMapView overlays]];
            _trackingIndex = 0;
            [_saveCoor removeAllObjects];
            break;
        case 1:
            _mainMapView.userTrackingMode = MKUserTrackingModeFollow;
            _trackingIndex = 1;
            break;
        case 2:
            _mainMapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
            _trackingIndex = 1;
            break;
        default:
            break;
    }
}


#pragma mark - CLLcationManagerDelegate Methods
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {

    CLLocation *currentLocation = locations.lastObject;
    NSLog(@"Current Location:%.6f,%.6f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    
    //make the region change just once
    static dispatch_once_t onceToken;
    //下面{}裡面的程式碼只會執行一次 不管整個方法跑幾次
    dispatch_once(&onceToken, ^{
        MKCoordinateRegion region = _mainMapView.region; //region代表地圖的中心和縮放大小
        region.center = currentLocation.coordinate;
        region.span.latitudeDelta = 0.01; //地圖上看最上緣跟最下緣相差0.01緯度
        region.span.longitudeDelta = 0.01;//...
        [_mainMapView setRegion:region animated:true];
//        [self uploadCurrentLocationToServer:currentLocation.coordinate.latitude longitude:currentLocation.coordinate.longitude];
        
    });
    _coor = currentLocation.coordinate;
    NSDictionary *setposition = @{@"latitude":@(_coor.latitude),
                                  @"longitude":@(_coor.longitude)};
    
    [self.saveLocation addObject:setposition];

    [[NSUserDefaults standardUserDefaults] setObject:self.saveLocation forKey:@"notes"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if(_trackingIndex == 1){
        [self drawMap];
    }
}

//-(void)uploadCurrentLocationToServer:(double)latitude longitude:(double)longitude{
//    NSString *urlString = [NSString stringWithFormat:@"http://class.softarts.cc/FindMyFriends/updateUserLocation.php?GroupName=ap102&UserName=Handsome_Joe&Lat=%.6f&Lon=%.6f",latitude,longitude];
//    NSURL *url = [NSURL URLWithString:urlString];
//    //Prepare NSURLSession
//    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
//    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//        if(error){
//            NSLog(@"Error:%@",error);
//            return;
//        }
//        //Convert NSData to NSString
//        NSString * content = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//        NSLog(@"Server Reply :%@",content);
//    }];
//    [task resume];
//}

- (IBAction)clickToFindFriends:(UIButton *)sender {
    NSString *urlString = @"http://class.softarts.cc/FindMyFriends/queryFriendLocations.php?GroupName=ap102";
    NSURL *url = [NSURL URLWithString:urlString];
    //Prepare NSURLSession
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(error) {
            NSLog(@"Error:%@",error);
            return;
        }
        NSDictionary * jsonObj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",jsonObj);
        NSArray * memberinfo = [[NSArray alloc]initWithArray:[jsonObj objectForKey:@"friends"]];
        NSLog(@"%@,%lu",memberinfo,(unsigned long)memberinfo.count);
        for(int idx=0; idx<memberinfo.count; idx++) {
            NSDictionary *memberSingleInfo = memberinfo[idx];
            
            CLLocationCoordinate2D memberLocation;
            memberLocation.latitude = [[memberSingleInfo objectForKey:@"lat"]floatValue];
            memberLocation.longitude = [[memberSingleInfo objectForKey:@"lon"]floatValue];
            NSString * memberName = [memberSingleInfo objectForKey:@"friendName"];
            NSLog(@"lat:%.6f,lon:%.6f,name:%@",memberLocation.latitude,memberLocation.longitude,memberName);
            MKPointAnnotation * annotation = [MKPointAnnotation new];
            annotation.coordinate = memberLocation;
            annotation.title = memberName;
            
            [_mainMapView addAnnotation:annotation];
        }
    }];
    [task resume];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    CLLocationCoordinate2D coord = [userLocation coordinate];
    
//    CLLocation *currentLocation = locations.lastObject;
//    NSLog(@"Current Location:%.6f,%.6f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    
    //make the region change just once
    static dispatch_once_t onceToken;
    //下面{}裡面的程式碼只會執行一次 不管整個方法跑幾次
    dispatch_once(&onceToken, ^{
        MKCoordinateRegion region = _mainMapView.region; //region代表地圖的中心和縮放大小
        region.center = coord;//currentLocation.coordinate;
        region.span.latitudeDelta = 0.01; //地圖上看最上緣跟最下緣相差0.01緯度
        region.span.longitudeDelta = 0.01;//...
        [_mainMapView setRegion:region animated:true];
        //        [self uploadCurrentLocationToServer:currentLocation.coordinate.latitude longitude:currentLocation.coordinate.longitude];
        
    });
    _coor = coord;//currentLocation.coordinate;
    NSDictionary *setposition = @{@"latitude":@(_coor.latitude),
                                  @"longitude":@(_coor.longitude)};
    
    [self.saveLocation addObject:setposition];
    
    [[NSUserDefaults standardUserDefaults] setObject:self.saveLocation forKey:@"notes"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if(_trackingIndex == 1){
        [self drawMap];
    }
}

- (void)drawMap {
    //_coor = CLLocationCoordinate2DMake(_latitude.doubleValue, _longitude.doubleValue);
    //NSLog(@"lat:%f,log:%f", _coor.latitude, _coor.longitude);
//    NSValue *value = [NSValue valueWithMKCoordinate:_coor];
//    [_saveCoor addObject:value];
//    CLLocationCoordinate2D coordinates[_saveCoor.count];
//    
//    for (int idx = 0; idx < _saveCoor.count; idx++) {
//        coordinates[idx] = [[_saveCoor objectAtIndex:idx] MKCoordinateValue];
//    }
//    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:_saveCoor.count];
//    [self.mainMapView addOverlay:polyLine];
    MapAnnotation *annotation = [self.mainMapView annotations].firstObject;
    if (!annotation) {
        annotation = [[MapAnnotation alloc] initWithCoordinate:_coor];
        [self.mainMapView addAnnotation:annotation];
    } else {
        annotation.coordinate = _coor;
    }
}

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id < MKOverlay >)overlay {
//    if ([overlay isKindOfClass:[MKPolyline class]]) {
//        MKPolyline *route = overlay;
//        MKPolylineRenderer *routeRenderer = [[MKPolylineRenderer alloc] initWithPolyline:route];
//        routeRenderer.strokeColor = [UIColor redColor];
//        routeRenderer.lineWidth = 5;
//        return routeRenderer;
//    }
    return nil;
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    MKAnnotationView *aView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"xx"];
    if (!aView) {
        aView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"xx"];
        aView.image = [UIImage imageNamed:@"img"];
        aView.clipsToBounds = YES;
        aView.bounds = CGRectMake(0, 0, 50, 50);
    }
    return aView;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    NSLog(@"xx");//
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    RecordPositionViewController * nextOrderPage = (RecordPositionViewController*)segue.destinationViewController;
    nextOrderPage.getPosition = self.saveLocation;
}

@end
